package com.ktjy.ktmall.servlet;

import com.alibaba.fastjson.JSONArray;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.BannerItem;
import com.ktjy.ktmall.service.BannerItemService;
import com.ktjy.ktmall.service.impl.BannerItemServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

// 用于接收并处理轮播图相关的请求
@WebServlet(name = "BannerItemServlet", urlPatterns = "/uni/home/banner")
public class BannerItemServlet extends HttpServlet {
    BannerItemService service = null;
    @Override
    public void init(ServletConfig config) throws ServletException {
        service = new BannerItemServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接收从小程序端传递过来的type和opr参数
        Integer type = Integer.valueOf(request.getParameter("type"));
        String opr = request.getParameter("opr");
        PrintWriter out = response.getWriter();
        AjaxResult result = null;  // 创建后端返回值封装类对象
        if ("list".equals(opr)) {
            // 根据跳转类型获取轮播图数据列表数据
            List<BannerItem> list = service.findByType(type);
            result = AjaxResult.success("轮播图列表加载成功!", list);
        }
        // 将result对象转换成JSON字符串再响应到小程序端
        out.print(JSONArray.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void destroy() {
        service = null;
    }
}
